package com.qf.drbackend.controller;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qf.drbackend.dtos.OrdersDto;
import com.qf.drbackend.pojos.OrderDetail;
import com.qf.drbackend.pojos.Orders;
import com.qf.drbackend.pojos.R;
import com.qf.drbackend.server.OrderDetailService;
import com.qf.drbackend.server.OrdersService;
import com.qf.drbackend.utils.DataUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

@RestController
@RequestMapping("/order")
@Slf4j
public class OrderController {

    @Autowired
    private OrdersService ordersService;

    @Autowired
    private OrderDetailService orderDetailService;

    @GetMapping("/userPage")
    public R listOrders(Integer page,Integer pageSize){
        if (page == null || page <=0){
            page = 1;
        }
        if (pageSize == null || pageSize <= 0){
            pageSize = 5;
        }

        Object uid = SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        IPage ipage = new Page<>(page,pageSize);
        Wrapper qw = Wrappers.lambdaQuery(Orders.class)
                .eq(Orders::getUserId,uid)
                .orderByDesc(Orders::getOrderTime);
        ordersService.page(ipage,qw);

        List<Orders> ordersList = ipage.getRecords();

        List<OrdersDto> ordersDtoList = new ArrayList<>();
        for (Orders orders : ordersList) {
            //异构页面所需数据
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(orders,ordersDto);

            qw = Wrappers.lambdaQuery(OrderDetail.class)
                    .eq(OrderDetail::getOrderId,orders.getId());
            List<OrderDetail> detailList = orderDetailService.list(qw);

            ordersDto.setOrderDetails(detailList);

            if (detailList != null)
                ordersDto.setSumNum(detailList.size());

            ordersDtoList.add(ordersDto);
        }


        ipage.setRecords(ordersDtoList);
        return R.success(ipage);
    }

    @GetMapping("/submit")
    public void submit(HttpServletRequest request, HttpServletResponse resp) throws AlipayApiException, IOException {
        Map<String, String[]> reqMap = request.getParameterMap();

        Map map = flatMap(reqMap);

        log.info("提交订单传递到后台的数据： {}",map);

        //获取前台页面传递过来的下单时唯一标识
        Object obj = map.get("orderBs");
        String pageOrderBs = null;
        if (obj != null)
            pageOrderBs = obj.toString();

        //获取之前后台生成的唯一标识
        String uid = (String) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        String orderBs = null;
        synchronized (uid) {
            Object data = DataUtils.getData(uid);
            if(data != null)
                orderBs = (String) data;
            DataUtils.removeData(uid);
        }

        if (orderBs!=null && orderBs.equals(pageOrderBs)){
            //可以下单 -- 清除
            ordersService.submit(map,resp);
            return;
        }


        R<Object> r = R.error("请不要重复下单");
        resp.setContentType("text/html;charset=utf-8");
        resp.getWriter().write(JSON.toJSONString(r));
    }

    /**
     * 将前台接收到的数组类型的value转成字符串类型的value
     * @param reqMap
     * @return
     */
    private Map flatMap(Map<String, String[]> reqMap) {
        HashMap map = new HashMap();

        Set<String> keys = reqMap.keySet();
        for (String key : keys) {
            String[] values = reqMap.get(key);
            if (values!=null && values.length>0){
                String value = values[0];
                map.put(key,value);
            }
        }

        return map;
    }
}
